<?php


namespace app\common\model;


use think\Db;

class CouponReceive extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_coupon_receive';
    // 主键ID
    protected $pk = 'receive_id';


    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*')
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    // h5获取用户领取消费券列表
    function user_coupon_list($userid,$limit){
        $where = [
            ["c.user_id",'=',$userid],
            ["c.is_use",'=',1],
        ];
        $field = [
            'c.*',
//            'case when (select count(*) from ddt_coupon_receive cr where cr.coupon_id = c.coupon_id and user_id = '.$userid.' and cr.is_use in (1,2))>0 then 1 else 0 end as is_get'
        ];
        $data = $this
            ->alias('c')
            ->field($field)
            ->where($where)
            ->paginate($limit);

//        echo $this->getLastSql();die;
        return $data;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['receive_id' => $id];
//            $params['update_time'] = time();
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            // 新增数据
            $params['add_time'] = time();
            $this->allowField(true)->save($params);
            $rs = $this->receive_id;
        }
//        $asdf =$this->getLastSql();
//        var_dump($asdf);die;
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }


}